package com.cast508.basic.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;


public class SpringContextUtils implements ApplicationContextAware{

    private static ApplicationContext context;
    private final static Logger logger = LoggerFactory.getLogger(SpringContextUtils.class);

    public static <T> T getBean(Class<T> requiredType){
        try {
            checkApplicationContext();
            return context.getBean(requiredType);
        }
        catch (Exception e) {
            logger.warn("[SpringContextUtils][getBean] error", e);
            return null;
        }
    }
    
    
    public static Object getBean(String name) {
        try {
            checkApplicationContext();
            return context.getBean(name);
        }
        catch (Exception e) {
            logger.warn("[SpringContextUtils][getBean] error", e);
            return null;
        }
    }
    
    public static ApplicationContext getApplicationContext(){
        checkApplicationContext();
        return context;
    }
    

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.context = applicationContext;
    }
    
    private static void checkApplicationContext()
    {
        if (context == null)
        {
            throw new IllegalStateException("SpringContextUtils��ApplicationContextΪ��");
        }
    }
    

}
